<template>
  <div class="page-container">
    <div class="system-menu-search mb15 FlexBox">
      <el-input
        placeholder="请输入菜单名称"
        v-model="state.searchMenu"
        @keyup.enter.native="onSearchMenu"
        style="max-width: 260px"
      >
      </el-input>
      <el-button icon="Search" type="primary" class="ml10"> 查询 </el-button>
      <button class="addBtn-small ml12" @click="onOpenAddMenu"><FolderAdd style="width: 1.1em; height: 1.1em;" /> 新增菜单 </button>
    </div>
    <fyh-table
      :data="state.dataList"
      v-chartLoading="{ loading: state.loading, time: 500 }"
      row-key="path"
      :tree-props="{ children: 'children', hasChildren: 'children' }"
      :cell-style="{
        borderTop: `1px solid #4485b5`
      }"
      :header-cell-style="headerCellStyle"
      :module-path="`views/system/menuMange`"
    >
      <template #svgIcon="{ row }">
        <div class="FlexBox absolute posTCenter left-40 gap-10">
          <svg-icon
            :name="row.meta.icon"
            :icon-style="{
              width: '16px',
              height: '16px',
              fill: '#7a85a4'
            }"
          />
          {{ row.meta.title }}
        </div>
      </template>
      <template #operation="{ row }">
        <el-button icon="Plus" :disabled="!row.children" text type="primary" @click="onOpenEditMenu('add', row)">新增</el-button>
        <el-button icon="EditPen" text type="primary" @click="onOpenEditMenu('update', row)">修改</el-button>
        <el-button icon="Delete" text type="primary">删除</el-button>
      </template>
    </fyh-table>
    <theDialog
      title="添加菜单"
      width="670px"
      clickConfirmNoclose
      v-model:visible="formOptions.visiable"
      @confirm="confirmHandleMenu"
    >
      <handleDialog ref="menuDialogRef" v-model="formOptions.model" :formOptions="formOptions.op">
        <template #IconSelector="rawData">
          <el-input ref="IconInputRef" v-model="rawData.val.meta.icon" placeholder="请选择图标名称">
            <template #prepend>
              <el-button>选择图标</el-button>
            </template>
            <template #append>
              <svg-icon :name="rawData.val.meta.icon" :icon-style="iconStyle"></svg-icon>
            </template>
          </el-input>
          <el-popover
            placement="bottom"
            width="500px"
            transition="el-zoom-in-top"
            popper-class="icon-selector-popper"
            trigger="click"
            :virtual-ref="IconInputRef"
            virtual-triggering
          >
            <template #default>
              <div class="flex gap-10" style="flex-wrap: wrap">
                <svg-icon
                  @click="rawData.val.meta.icon = v"
                  v-for="v in sheetsIconList"
                  :name="v"
                  :icon-style="iconStyle"
                  class="svg-icon"
                />
              </div>
            </template>
          </el-popover>
        </template>
      </handleDialog>
    </theDialog>
  </div>
</template>

<script setup lang="ts" name="systemMenu">
import { useMessage, useMessageBox } from "@/hooks/message";
import { pageList, handleMenu } from "@/api/admin/menu";
import { useTable, BasicTableProps } from "@/hooks/tablePage";
import FyhTable from "@/components/FyhComs/FyhTable.vue";
import theDialog from "@/components/Dialog/index.vue";
import { ElPopover } from "element-plus";
import { useIconsStore } from "@/stores/modules/icons";
import MenuOp, { permission, component, defaultColum, routerName, keepAlive } from "./formOptions";
const iconStyle = { width: "18px", height: "18px" };
const baseFormModel = (options: Partial<formOpType["model"]> = {}): formOpType["model"] => {
  const result = Object.assign(
    {
      path: "",
      component: "",
      redirect: "",
      name: "",
      menuType: "目录",
      parent: "parent",
      meta: {
        icon: "",
        title: "",
        isHide: 'false',
        isFull: 'false',
        isAffix: 'false',
        isLink: "",
        permission: "",
        sort: '0',
        activeMenu: "",
        status: 'true',
        isKeepAlive: 'true'
      }
    },
    options
  );
  return result;
};
interface formOpType {
  visiable: boolean;
  op: FyhComOptions;
  model: Menu.MenuOptions & { menuType?: "目录" | "菜单" };
}
// 引入组件
const handleDialog = defineAsyncComponent(() => import("@/components/FyhComs/FyhForm.vue"));
const menuDialogRef = ref<InstanceType<typeof handleDialog>>();
const IconInputRef = ref();
const sheetsIconList = computed(() => useIconsStore().iconList);
const dialogHandleType = ref<"add" | "update">("add");
const state = reactive<BasicTableProps<Menu.MenuOptions>>({
  pageList,
  searchMenu: ""
});
const formOptions = reactive<formOpType>({
  visiable: false,
  op: MenuOp,
  model: baseFormModel()
});
const { getDataList, tableStyle } = useTable(state);
const { headerCellStyle } = toRefs(tableStyle());
// 打开新增菜单弹窗
const onOpenAddMenu = () => {
  dialogHandleType.value = "add";
  formOptions.model = baseFormModel({
    parent: "parent",
  });
  formOptions.visiable = true;
};
const onSearchMenu = () => {
  // state.dataList = state.dataList?.map
};
// 打开编辑菜单弹窗
const onOpenEditMenu = (type: "add" | "update", row: formOpType["model"]) => {
  dialogHandleType.value = type;
  if (type === "add") {
    formOptions.model = baseFormModel({
      parent: row.path
    });
  } else {
    formOptions.model = row;
  }
  formOptions.model.menuType = type === "add" ? "目录" : row.children ? "目录" : "菜单";
  formOptions.visiable = true;
};
const confirmHandleMenu = async () => {
  const valid = await menuDialogRef.value!.FyhFormRef!.validate();
  if (!valid) return;
  const params = toRaw(formOptions.model);
  for (const key of ['isHide','isFull','isAffix','sort','status','isKeepAlive']) {
    // @ts-ignore
    params.meta[key] = JSON.parse(params.meta[key]);
  }
  await handleMenu(params, "authMenuList", dialogHandleType.value);
  useMessage().success("菜单操作成功");
  getDataList();
};
const handleWatcher = (newValue: formOpType["model"]["menuType"], oldValue: formOpType["model"]["menuType"]) => {
  if (newValue === "目录") {
    formOptions.op.columns = defaultColum();
  } else {
    formOptions.op.columns.splice(4, 1);
    formOptions.op.columns.splice(4, 0, [routerName, keepAlive], [permission, component]);
  }
};
watch(() => formOptions.model.menuType, handleWatcher);
</script>
<style lang="scss" scoped>
:deep(.flexForm .el-form-item) {
  margin-bottom: 18px !important;
}
</style>
